package comqyf.nacoscloudzookeeper.lock;


import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMultiLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ZooLock {
    private static final String LOCK_PATH = "/qyf/locks";

    private static final Map<String, InterProcessMutex> mutexMap = new ConcurrentHashMap<>();

    @Autowired
    private CuratorFramework client;

    private InterProcessMutex getMutex(String lockName) throws Exception{
        InterProcessMutex mutex = mutexMap.get(lockName);
        if (mutex == null){
            mutexMap.putIfAbsent(lockName, new InterProcessMutex(client, LOCK_PATH + "/" + lockName));
            return mutexMap.get(lockName);
        }
        return mutex;
    }

    public void lock(String lockName, long time, TimeUnit timeUnit) throws Exception{
        InterProcessMutex mutex = getMutex(lockName);
        try {
            mutex.acquire(time, timeUnit);
        } catch (Exception e) {
            log.error("lock fail log error message:{}", e);
        }
    }

    public void lock(String lockName) throws Exception{
        InterProcessMutex mutex = getMutex(lockName);
        try {
            mutex.acquire();
        } catch (Exception e) {
            log.error("lock fail log error message:{}", e);
        }
    }


    public void unlock(String lockName) throws Exception {
        InterProcessMutex mutex = getMutex(lockName);
        try {
            mutex.release();
        } catch (Exception e) {
            log.error("unlock fail log error message:{}", e);
        }
    }


}
